<?
/**
 * VoiceOne Webservices Interface
 *
 * @package voiceone_webservices
 * @subpackage  voicemail
 */

//******************************************************************************
//******************               VOICE MAIL              *********************
//******************************************************************************

// ---- getVoiceMail(id:int):VoiceMail[] ---------------------------------------
function getVoiceMail($id) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE mailbox=$id ";
  $qry="SELECT * FROM voicemail_users $condition ORDER BY mailbox";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) { 
    $arr["id"]=$arr["uniqueid"];
    $ret[]=$arr;
  }
  return $ret;
}

// ---- putVoiceMail(voicemail:VoiceMail):int ---------------------------------------
function putVoiceMail($voicemail) {
  global $db;
  $id="";
  $id_value="";
  
  //if already exists, delete it
  if (isset($voicemail["mailbox"]) and $voicemail["mailbox"]!="") {
    delVoiceMail($voicemail["mailbox"],false);
  } else return 0; //no mail box is defined
  
  //insert the mailbox
  $qry="INSERT INTO voicemail_users (context, mailbox, password, fullname, email, pager, attach, saycid, hidefromdir) ";
  $qry.="VALUES ('default', \"{$voicemail['mailbox']}\",\"{$voicemail['password']}\",\"{$voicemail['fullname']}\",\"{$voicemail['email']}\",\"{$voicemail['pager']}\",\"{$voicemail['attach']}\",\"{$voicemail['saycid']}\",\"{$voicemail['hidefromdir']}\")";
  $res=$db->Execute($qry);
  
  if ($res===false) $ret=0; 
  else return $voicemail["mailbox"]; 
}
  
// ---- delVoiceMail(id:int):int ---------------------------------------
function delVoiceMail($mailbox) {
  global $db;
  $qry="DELETE FROM voicemail_users WHERE mailbox=$mailbox";
  $res=$db->Execute($qry);
  if ($res===false) $ret=0; 
  else return 1;
}

/**
 * Get a list of the extension's voicemails. The list is an array of VoiceMailStructure: 
 * for every message it reports filename, callerid, date and duration
 *
 * @param string $exten user extension
 * @return array $messages tns:VoiceMailStructureArray with description of voicemail messages
 * @see checkVoiceMailMessage
 * @see changeVoiceMailMessageGroup
 * @see deleteVoiceMailMessage
 */
function getVoiceMailList($exten) {
  global $voTools, $voiceoneWSDocumentRoot;
  //move audio files to sandbox
  $topath = $voiceoneWSDocumentRoot."/sandbox";
  exec("sudo $voTools voicemail $exten $topath",$output,$retScript);
  $file_list = $topath."/voicemail/".$exten."/".$exten."_list.txt";
  $file_msg = $topath."/voicemail/".$exten."/".$exten."_msg.txt";
  // Open $exten_list file, and extract messages files name
  if (is_file($file_list)) {
    $lines = file($file_list);
    foreach($lines as $line){
      if ((substr($line,0,-1)=="INBOX")||(substr($line,0,-1)=="Old")||(substr($line,0,-1)=="Family")
         ||(substr($line,0,-1)=="Friends")||(substr($line,0,-1)=="Work")){
        $type=$line;
      }
      else $list[]=substr($type,0,-1)."/".$line;
    } 
  }
  // Open $exten_msg file, and extract information
  if (is_file($file_msg)) {
    $lines = file($file_msg);
    $i=0;
    foreach($lines as $line) {
      if (strpos($line,"=")>0) {
        $arr=split("=",$line);
        if ($arr[0]=="callerid") $output["callerid"]=$arr[1];
        if ($arr[0]=="origdate") $output["origdate"]=$arr[1];
        if ($arr[0]=="duration") {
          $output["duration"]=$arr[1];
          $output["filename"]= $list[$i];
          $messages[]=$output;
          $i++;
          unset($output);
        }
      }
    }
  }
  return $messages;
}

/**
 * Check if a voicemail message is in voiceone_ws's sandbox. If not, it copy it in sandbox 
 *
 * @param string $exten user extension
 * @param string $filename message to check
 * @return int $ret 1 if message is present, 0 if not
 * @see getVoiceMailList
 * @see changeVoiceMailMessageGroup
 * @see deleteVoiceMailMessage
 */
function checkVoiceMailMessage($exten, $filename) {
  global $voTools, $voiceoneWSDocumentRoot;
  $groupTmp=split('/',$filename);
  $group=$groupTmp[0];
  $file=$groupTmp[1];
  $topath = $voiceoneWSDocumentRoot."/sandbox";
  $message = $topath."/voicemail/".$exten."/".$group."/".$file;
  // Check file exists
  $nowExists=false;
  if(!(file_exists($message))){ 
    // Copy $filename from /var/spool/asterisk/voicemail/default/$exten 
    //                to  /$topath/voicemail/$exten
    exec("sudo $voTools transferVoiceMailMessage $exten $topath $file $group",$output,$retScript); 
    if(file_exists($message)){ $nowExists=true;}
  } 
  else{ 
    // File already in ws's folder
    $nowExists=true;
  } 
  if($nowExists===false){return 0;}
  // Open php stream
  return 1;
}

/**
 * Change the message filename and group. It change the four files relative 
 * to one voicemail message (.txt .gsm .WAV . wav)
 *
 * @param string $exten user extension
 * @param string $tofilename new message name
 * @param string $togroup new message group
 * @param string $filename old message name
 * @param string $group old message group
 * @return int $ret 1 if ok, 0 if not
 * @see getVoiceMailList
 * @see checkVoiceMailMessage
 * @see deleteVoiceMailMessage
 */
function changeVoiceMailMessageGroup($exten, $tofilename, $togroup, $filename, $group) {
  global $voTools;
  // move file.txt && file.wav && file.WAV && file.gsm
  $totxt = $tofilename.".txt";
  $txt = $filename.".txt";
  exec("sudo $voTools messageChangeFolder $exten $totxt $togroup $txt $group",$output,$retScript);
  $towav = $tofilename.".wav";
  $wav = $filename.".wav";
  exec("sudo $voTools messageChangeFolder $exten $towav $togroup $wav $group",$output,$retScript);
  $toWAV = $tofilename.".WAV";
  $WAV = $filename.".WAV";
  exec("sudo $voTools messageChangeFolder $exten $toWAV $togroup $WAV $group",$output,$retScript);
  $togsm = $tofilename.".gsm";
  $gsm = $filename.".gsm";
  exec("sudo $voTools messageChangeFolder $exten $togsm $togroup $gsm $group",$output,$retScript);
  return 1;
}

/**
 * Delete a voicemail message
 *
 * @param string $exten user extension
 * @param string $filename message to delete
 * @return int $ret 1 if ok, 0 if not
 * @see getVoiceMailList
 * @see checkVoiceMailMessage
 * @see changeVoiceMailMessageGroup
 */
function deleteVoiceMailMessage($exten, $filename) {
  global $voTools;
  //delete $filename from /var/spool/asterisk/voicemail/default/$exten
  exec("sudo $voTools deleteVoicemailMessage $exten $filename",$output,$retScript);
  return 1;
}

/**
 * Record an answer message with floAPI
 *
 * @param string $clientId user id
 * @param string $filename message name 
 * @return int $ret 1 if ok, 0 if not
 * @see getVoiceMailAnswers
 * @see deleteVoiceMailAnswer
 * @see setVoiceMailAnswer
 */
function recordVoiceMailAnswer($clientId, $filename) {
  global $voTools,$floapi,$API_user,$API_pass,$API_host;
  $ret=getApplicationByName("audiorecorder");
  $AUDIO_RECORDER_APPLICATION=$ret["id"];
  //retrieve some information from db
  $channelArr=getChannel(getChannelFromEntity($clientId));
  $channelName=$channelArr[0]["name"];
  $clientArr=getClient($clientId,0);
  $client=$clientArr[0];
  $ruleId=$client["rule"];
  $ruleArr=getRule($ruleId);
  $ruleName=$ruleArr[0]["name"];
  $applicationArr=getApplication($AUDIO_RECORDER_APPLICATION);
  $application=$applicationArr[0];
  $appExtension=$application["extension"];
  //originate the call and save audio message in var/lib/asterisk/sounds/voiceone/voicemail
  $entry=array('Channel'=>$channelName,'Exten'=>$appExtension,'Context'=>$ruleName,'Priority'=>1,'Callerid'=>"VoiceMail Audio Recorder <$filename>");
  $floapi = new floAPI($API_user, $API_pass, $API_host);
  if ($floapi->socket!="") {
    $ret=$floapi->request("Originate", $entry);
    $floapi->close();
  } 
  else return 0;
  return 1;
}

/**
 * Get a list of the answer messages. The list contains the recorded message 
 * and the setted message. For every message it reports filename and md5 sum
 *
 * @param string $exten user extension
 * @return array $answers tns:AnswerMessageStructureArray
 * @see recordVoiceMailAnswer
 * @see deleteVoiceMailAnswer
 * @see setVoiceMailAnswer
 */ 
function getVoiceMailAnswers($exten) {
  global $voTools, $voiceoneWSDocumentRoot;
  $topath = $voiceoneWSDocumentRoot."/sandbox";
  exec("sudo $voTools getVoiceMailAnswers $exten $topath",$output,$retScript);
  $file_answers = $topath."/voicemail/".$exten."/".$exten."_answers.txt";
  // Open $exten_answers file, and extract messages files name
  if (is_file($file_answers)) {
    $lines = file($file_answers);
    foreach($lines as $line){
      if(substr($line,0,1)!="*"){
        list ($md5, $file_long) = split ('  ', $line);
        $ret=ereg(".*/(.*)\.gsm", $file_long, $file_arr);
        if($ret!==false){
          $filename = $file_arr[1];
          $output["filename"] = $filename;
          $output["md5"] = rtrim($md5);
        }
      }
      else{
        list ($filename, $md5, $file_long) = split (' ', $line);
        $output["filename"] = $filename;
        $output["md5"] = rtrim($md5);
      }
      $answers[]=$output;
      unset($output);
    } 
  }
  return $answers;
}

/**
 * Delete an answer message
 *
 * @param string $exten user extension
 * @param string $filename answer message to delete 
 * @return int $ret 1 if ok, 0 if not
 * @see recordVoiceMailAnswer
 * @see getVoiceMailAnswers
 * @see setVoiceMailAnswer
 */
function deleteVoiceMailAnswer($exten, $filename) {
  global $voTools;
  exec("sudo $voTools deleteVoiceMailAnswer $exten $filename",$output,$retScript);
  return 1;
}

/**
 * Set a recorded message as answer message. The type of answer message can be 
 * unavailable ("unavail"), busy ("busy"), temporary greeting ("temp") or your name ("greet")
 *
 * @param string $exten user extension
 * @param string $filename answer message to set
 * @param string $type type of answer message
 * @return int $ret 1 if ok, 0 if not
 * @see recordVoiceMailAnswer
 * @see getVoiceMailAnswers
 * @see deleteVoiceMailAnswer
 */
function setVoiceMailAnswer($exten, $filename, $type) {
  global $voTools;
  error_log("avvio");
  exec("sudo $voTools setVoiceMailAnswer $exten $filename $type",$output,$retScript);
  return 1;
}